#include <stdio.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h> 
#include <net/if.h>
#include <sys/ioctl.h>

#ifdef PKT_SEND_FUNCTION
int pktsnd(int argc, char **argv)
#else
int main(int argc, char *argv[])
#endif
{
	int sockfd;
	int CR157=0;
	unsigned char buf[2048];	
	struct sockaddr_ll sll,sll2;
	int  j;
	struct ifreq iface;
	int ifidx;
	unsigned char MAC[20];
	int length, cnt, pattern;


	if(argc != 12)  {
		printf("Wrong parameter number\n");
		printf("program eth length cnt pattern m1 m2 m3 m4 m5 m6 other\n");
		printf("Ex:\n");
		printf("   pkt_send eth1 1000 10000 127 ff ff ff ff ff ff NO\n");
		return -1;
	}


	sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	if (sockfd == -1) {
		printf("Open Socket Error\n");
		return -1;
	}

	memset(&iface, 0, sizeof(struct ifreq));
	strncpy(iface.ifr_name, argv[1], IFNAMSIZ);
	if (ioctl(sockfd, SIOCGIFINDEX, &iface) == -1) {
		printf("Get Interface Index Error");
		return -1;
	}
	ifidx=iface.ifr_ifindex;
	
	memset(&iface, 0, sizeof(struct ifreq));
	strncpy(iface.ifr_name, argv[1], IFNAMSIZ);
	if (ioctl(sockfd, SIOCGIFHWADDR, &iface) == -1) {
		printf("Get MAC Address Error\n");
		return -1;
	}
	
	memset(&sll, 0xff, sizeof(sll));
	sll.sll_family = AF_PACKET;	
	sll.sll_protocol = htons(ETH_P_ALL);
	sll.sll_ifindex = ifidx;
	if (bind(sockfd, (struct sockaddr *)&sll, sizeof sll) == -1) {
		printf("binding error\n");
		return -1;
	}
	
	length = atoi(argv[2]);
	
	cnt = atoi(argv[3]);
	pattern = atoi(argv[4]);

	sscanf(argv[5],"%x",&MAC[0]);
	sscanf(argv[6],"%x",&MAC[1]);
    sscanf(argv[7],"%x",&MAC[2]);
    sscanf(argv[8],"%x",&MAC[3]);
    sscanf(argv[9],"%x",&MAC[4]);
    sscanf(argv[10],"%x",&MAC[5]);
	sscanf(argv[11],"%x", &CR157);

	
	
	for (j=0; j<cnt; j++)
	{
			memset(buf,0,sizeof(buf));
			memcpy(buf, MAC, ETH_ALEN);
			memcpy(buf+6,iface.ifr_hwaddr.sa_data,ETH_ALEN);
			buf[12]=0x08;
			buf[13]=0x00;
			if((pattern & 0x0000ff00) == 0x0100) {
				strcpy(buf+14+10, "ZyDASIQTEST"); //10 is from testing...
				buf[14+10+11] = 0xff & CR157; //11 is the lenof ZyDASIQ...
				length = 26+10;  //Total Length is 36
			}
			else
				memset(buf+14,(char)(pattern&0xff),1487);
			//memset(buf+14, 85,1487);
			memset(&sll2, 0,sizeof(sll2));
			sll2.sll_ifindex = ifidx;

			if(sendto(sockfd, buf, length>1487?1487:length, 0, 
				(struct sockaddr *)&sll2, sizeof(struct sockaddr_ll))==-1
			)
				printf("Sending Packet Error\n");

			
			
	}
	return 0;
}

